class loop_queue:
    def __init__(self, size):
        self.size = size
        self.queue = [0 for _ in range(size)]  # 初始化队列，所有元素为0
        self.front = 0  # 队头指针
        self.rear = 0  # 队尾指针

    def __str__(self):
        return str(self.queue[:])

    def is_empty(self):
        return self.front == self.rear

    def is_full(self):
        return (self.rear + 1) % self.size == self.front

    def enqueue(self, data, force=True):
        if force == False and self.is_full():
            raise Exception("queue is full")

        if self.is_full():
            self.front = (self.front + 1) % self.size

        self.rear = (self.rear + 1) % self.size
        self.queue[self.rear] = data

    def dequeue(self):
        if self.is_empty():
            raise Exception("queue is empty")

        data = self.queue[self.front]
        self.queue[self.front] = 0  # 清空出队的元素
        self.front = (self.front + 1) % self.size
        return data

    def get_front(self):
        if self.is_empty():
            raise Exception("queue is empty")

        return self.queue[self.front]

    def get_rear(self):
        if self.is_empty():
            raise Exception("queue is empty")

        return self.queue[self.rear]


if __name__ == "__main__":
    q = loop_queue(5)

    # 1.入队列
    q.enqueue(1)
    q.enqueue(2)
    q.enqueue(3)
    q.enqueue(4)
    # q.enqueue(5)
    q.enqueue(5, force=True)  # 强制入队，即使队列已满
    try:
        q.enqueue(6,force=False)
    except Exception as e:
        print(e)  # 队列已满，抛出异常

    print(q)  # 打印队列
    print(q.get_front())  # 获取队头元素
    print(q.get_rear())  # 获取队尾元素

    # 2.出队列
    q.dequeue()  # 出队一个元素
    print(q)
    print(q.get_front())
    print(q.get_rear())

    # 3.完全出队列
    while not q.is_empty():
        print(q.dequeue())  # 依次出队所有元素
    print(q)  # 打印队列，此时队列为空
